import { resolve } from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import { VueHooksPlusResolver } from '@vue-hooks-plus/resolvers'
import TurboConsole from 'unplugin-turbo-console/vite'
import LightningCSS from 'unplugin-lightningcss/vite'
import UnoCSS from 'unocss/vite'
import { createHtmlPlugin } from 'vite-plugin-html'
import VueDevTools from 'vite-plugin-vue-devtools'
import yaml from 'js-yaml'
import { templateCompilerOptions } from '@tresjs/core'

const vuePageMetaPlugin = {
  name: 'vue-page-meta',
  transform(code, id) {
    if(!/vue&type=page-meta/.test(id)) {
      return
    }
    if(id.includes('__client-dynamic') && /lang\.ya?ml$/.test(id)) {
      code = JSON.stringify(yaml.load(code.trim()))
    }
    // 将pageMeta的值挂载到组件示例
    return `export default Comp => {
      Comp.pageMeta = ${code}
    }`
  },
}

export default defineConfig(({ mode, command }) => {
  const envVars = loadEnv(mode, process.cwd(), '')

  const plugins = [
    vue({
      ...templateCompilerOptions,
    }),
    vuePageMetaPlugin,
    Components({
      dirs: ['src/components', 'src/pages/__view-unit'],
      resolvers: [NaiveUiResolver()],
      dts: 'src/components.d.ts',
    }),
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia',
        {
          'naive-ui': [
            'useDialog',
            'useMessage',
            'useNotification',
            'useLoadingBar',
          ],
        },
      ],
      eslintrc: {
        enabled: envVars.DEV,
        filepath: './.eslintrc-auto-import.json',
        globalsPropValue: true,
      },
      resolvers: [VueHooksPlusResolver()],
      dts: 'src/auto-imports.d.ts',
    }),
    UnoCSS({
      configFile: './uno.config.js',
    }),
    LightningCSS(),
  ]

  const define = {
    __INJECT_ENV_VARS__: {},
  }

  const rollupOptions = {
    output: {
      // Static resource classification and packaging
      chunkFileNames: 'static/js/[name]-[hash].js',
      entryFileNames: 'static/js/[name]-[hash].js',
      assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
      manualChunks: {
        vue: ['vue', 'vue-router', 'pinia'],
      },
    },
  }

  if(command === 'serve') {
    const dynamicEnvVars = ['--mode']
    process.argv.forEach((argv, index) => {
      let [key, value] = argv.split('=')
      if(index >= 2 && key && dynamicEnvVars.includes(key)) {
        key = key.replace('--', '')
        define.__INJECT_ENV_VARS__[key] = value
      }
    })
    plugins.push(
      TurboConsole({
        prefix: '',
        suffix: '',
        disableLaunchEditor: false,
        port: 5090,
      }),
    )
    plugins.push(VueDevTools())
  }

  // 需要最后注册的插件
  plugins.push(
    createHtmlPlugin({
      minify: true,
      inject: {
        data: { title: envVars.VITE_GLOB_APP_TITLE },
      },
    }),
  )

  return {
    base: './',
    build: {
      manifest: true,
      assetsDir: 'assets',
      rollupOptions,
      assetsInlineLimit: 1024 * 10,
      chunkSizeWarningLimit: 1024 * 20,
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
            @import "@/styles/variables.scss";
          `,
          javascriptEnabled: true,
        },
      },
    },
    json: {
      stringify: true,
    },
    define,
    esbuild: {
      pure: envVars.VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
    },
    plugins,
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    server: {
      port: 9090,
    },
  }
})
